<template>
	<view class="modifyInformation">
		<view class="bodyBox Column">
			<view class="bodyBox_childBox Row">
				<view class="title">头像</view>
				<view class="Row">
					<view class="avatar" @click="chooseImg">
						<image class="photoSize" :src="avatar" mode="aspectFill"></image>
					</view>
					<u-icon name="arrow-right" color="#9a9a9a" size="20"></u-icon>
				</view>
			</view>
			<view class="bodyBox_childBox Row">
				<view class="title flex-row items-center">用户名<view class="emphasis"
						v-if="information.username === 'u6'">*</view>
				</view>
				<view class="Row">
					<input class="input" type="text" placeholder="请输入用户名" :value="information.username"
						data-info="username" @input="setInfo" />
				</view>
			</view>
			<view class="bodyBox_childBox Row">
				<view class="title flex-row items-center">昵称<view class="emphasis"
						v-if="information.nickname === '微信用户'">*
					</view>
				</view>
				<view class="Row">
					<input class="input" type="text" placeholder="请输入昵称" :value="information.nickname"
						data-info="nickname" @input="setInfo" />
				</view>
			</view>
			<!-- <view class="bodyBox_childBox Column">
				<view class="title">个人简介</view>
				<view class="Row">
					<textarea class="textarea" placeholder="请输入个人简介" :value="information.Biography"
						data-info="Biography" @input="setInfo"></textarea>
				</view>
			</view> -->
		</view>

		<view class="bodyBox Column">
			<view class="bodyBox_childBox Row">
				<view class="title flex-row items-center">手机号<view class="emphasis" v-if="!mobile">*</view>
				</view>

				<view class="flex-row items-center" style="width: 70%;justify-content: flex-end;">
					<input style="width: 50%;" disabled class="input" type="text" placeholder="点击获取手机号"
						:value="mobile" />
					<button class="getPhoneNumber" open-type="getPhoneNumber"
						@getphonenumber="getPhoneNumber">获取手机号</button>
				</view>
			</view>

			<view class="bodyBox_childBox Row" v-if="inviter">
				<view class="title">绑定邀请人</view>
				<view class="flex-row items-center">已绑定 {{inviter}}</view>
			</view>
			<view class="bodyBox_childBox Row" v-else @click="showPopup = true">
				<view class="title flex-row items-center">绑定邀请人<view class="emphasis">*</view>
				</view>

				<u-icon name="arrow-right" color="#919191" size="16"></u-icon>
			</view>
		</view>

		<!-- 选择收货地址的盒子 -->
		<view class="addressChoose Row">
			<view class="btn" @click="save">保存</view>
		</view>

		<!-- 引入封装好的弹窗 -->
		<CustomPopup :visible="showPopup" @update:visible="showPopup = $event" />
	</view>
</template>

<script>
	import {
		apiUserProfile
	} from '@/api/weChat_login.js';
	import {
		uploadImage
	} from '@/utils/util.js';
	import {
		apiBindInviter,
		apiGetPhoneNumber
	} from '@/api/weChat_login.js';
	import CustomPopup from '@/components/user-info/user-info.vue'

	export default {
		components: {
			CustomPopup
		},
		data() {
			return {
				showPopup: false,
				show: false,
				userInfo: {},
				inviter: uni.getStorageSync("inviter").nickname,

				avatar: '',
				mobile: '',
				information: {
					username: '',
					nickname: '',
					Biography: '',
				},

				inviterCode: '', // 扫描二维码
			};
		},
		onLoad(options) {
			const token = uni.getStorageSync('token');
			if (!token) {
				uni.redirectTo({
					url: `/pages/logIn/weChat_login/weChat_login?redirect=${encodeURIComponent(`/pages/mine/editInfomation/editInfomation?scene=${options.scene}`)}`
				})
				return;
			}
			
			// 如果有 scene 参数，解析邀请码
			if (options.scene) {
				this.parameterParsing(options);
			}
		},
		onShow() {
			// 初始化用户信息
			const userInfo = uni.getStorageSync('userInfo') || {};
			this.userInfo = userInfo;

			this.avatar = userInfo.avatar || '';
			this.mobile = userInfo.mobile || '';
			this.information = {
				username: userInfo.username || '',
				nickname: userInfo.nickname || '',
				Biography: userInfo.bio || ''
			}
		},
		methods: {
			parameterParsing(options) {
				const scene = decodeURIComponent(options.scene || '');
				const params = {}
				if (scene.includes('=')) {
					const [key, value] = scene.split('=')
					params[key] = value
				}

				this.scanCode(params.inviter_code);
			},

			scanCode(code) {
				let that = this;
				uni.showLoading({
					title: '加载中'
				});

				apiBindInviter({
					inviter_code: code
				}).then(res => {
					uni.hideLoading();
					if (!res.code) {
						uni.$u.toast(res.msg);
						return;
					}

					that.getUserInfo(); // 重新赋值本地缓存
					uni.$u.toast("绑定成功");
				}).catch(err => {
					uni.hideLoading();
					console.log(err);
				})
			},

			getUserInfo() {
				let that = this;
				uni.$u.http.post('/user/getUserInfo').then(res => {
					uni.setStorageSync("inviter", res.data.inviter);
					uni.setStorageSync("userInfo", res.data.userinfo);
					this.inviter = uni.getStorageSync("inviter").nickname;
				}).catch(err => {
					console.log(err)
				})
			},

			getPhoneNumber(res) {
				if (res.detail.errMsg === 'getPhoneNumber:ok') {
					// 用户同意授权，获取加密的手机号信息
					let code = res.detail.code;

					apiGetPhoneNumber({
						code
					}).then(res => {
						if (!res.code) return uni.$u.toast(res.msg);
						uni.setStorageSync("userInfo", res.data.userinfo);
						uni.$u.toast('保存成功');
						this.mobile = res.data.userinfo.mobile;
					}).catch(err => {
						uni.$u.toast(err.msg);
					})
					// 将加密信息发送到后端进行解密
				}
			},
			chooseImg() {
				uni.showLoading({
					title: '上传中',
					mask: true
				});

				uploadImage({
						count: 1,
						sourceType: ['album'],
						sizeType: ['original', 'compressed'],
						formData: {
							type: 'avatar'
						}
					})
					.then(avatarUrl => {
						uni.hideLoading();
						this.avatar = avatarUrl;
						uni.$u.toast("上传成功");
					})
					.catch(err => {
						uni.hideLoading();
						uni.$u.toast("上传失败：" + (err.message || '未知错误'));
					});
			},
			setInfo(e) {
				let name = e.currentTarget.dataset.info,
					value = e.detail.value.trim();
				this.information[name] = value;
			},

			// 保存
			save() {
				let that = this,
					information = that.information;

				if (information.username == '' || information.username === 'u6') {
					uni.$u.toast("用户名错误，请输入并修改用户名！");
					return;
				}
				if (information.nickname == '' || information.nickname === '微信用户') {
					uni.$u.toast("昵称错误，请输入并修改昵称！");
					return;
				}

				apiUserProfile({
					avatar: that.avatar,
					username: information.username,
					nickname: information.nickname,
					bio: information.Biography,
				}).then(res => {
					if (!res.code) return uni.$u.toast(res.msg);
					that.getUserInfo(); // 重新赋值本地缓存
					uni.$u.toast('保存成功');
					setTimeout(() => {
						uni.switchTab({
							url: '/pages/mine/mine' // 登录成功跳转首页
						});
					}, 1000)
				}).catch(err => {
					uni.$u.toast(err.msg);
				})
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #EFF3F4;
	}

	.addressChoose {
		z-index: 3;
		width: 95%;
		background-color: #fff;
		padding: 20rpx;
		position: fixed;
		left: 0;
		bottom: 0;

		.btn {
			width: 99%;
			text-align: center;
			font-size: 30rpx;
			color: #fff;
			background: #0056FF;
			border-radius: 40rpx;
			padding: 20rpx 0;
		}
	}

	.bodyBox {
		width: 89%;
		background-color: #fff;
		border-radius: 6px;
		padding: 12px 12px 16px 12px;
		margin: 12px auto 0;

		&_childBox:first-child {
			padding-top: 0 !important;
			padding-bottom: 18px !important;
		}

		&_childBox:last-child {
			padding-bottom: 0 !important;
		}

		&_childBox {
			justify-content: space-between;
			padding: 0 0 56rpx;

			.avatar {
				width: 100rpx;
				height: 100rpx;
				border-radius: 12rpx;
				margin-right: 4px;
				overflow: hidden;
			}

			.getPhoneNumber {
				color: #0056FF;
				height: 32px;
				line-height: 32px;
				font-size: 14px;
				background: #d7e5ff;
				border-radius: 60px;
				border: 1px solid #0056FF;
				margin: 0 0 0 8px;
			}

			.title {
				font-size: 32rpx;

				.emphasis {
					font-size: 14px;
					color: red;
					padding-left: 2px;
				}
			}

			.input {
				color: #888888;
				text-align: right;
			}

			.textarea {
				width: 100%;
				border-radius: 12rpx;
				background-color: #f9f9f9;
				padding: 20rpx;
				margin-top: 36rpx;
			}
		}
	}
</style>